package service;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class DownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 5388774889003027459L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filename = req.getParameter("name");
        filename = req.getServletContext().getRealPath("/uploaded/") + filename;
        File downloadFile = new File(filename);
        if (!downloadFile.exists()) {
            req.setAttribute("error", "请求下载的文件不存在，可能它已被删除或移动至其他位置");
            req.getRequestDispatcher("download.jsp").forward(req, resp);
            return;
        }
        // 设置响应头部（预下载的文件的名称应当被英文双引号引用，否则在火狐浏览器中可能出现包含空格的文件名被截断的问题）
        resp.setHeader("content-disposition", "attachment;filename=\"" + new String(downloadFile.getName().getBytes(), "ISO-8859-1") + "\"");
        // 读取预下载的文件将其保存至文件输入流
        FileInputStream fis = new FileInputStream(filename);
        // 创建输出流
        OutputStream os = resp.getOutputStream();
        // 创建缓冲区，循环将文件输入流中的内容读取至缓冲区
        byte[] buffer = new byte[4096];
        int length;
        while (0 <= (length = fis.read(buffer))) {
            // 使用输出流将缓冲区中的内容输出至浏览器端
            os.write(buffer, 0, length);
        }
        os.close();
        fis.close();
    }
}
